import { useState, useEffect } from 'react';
import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { stripeService } from '../services/stripe';
import { useLanguage } from '@kernelproxy/i18n';
import { useToast } from '../contexts/ToastContext';

interface StripeSetupFormProps {
  clientSecret: string;
  onSuccess: (paymentMethodId: string) => void;
  onCancel: () => void;
}

const StripeSetupForm = ({ clientSecret, onSuccess, onCancel }: StripeSetupFormProps) => {
  const stripe = useStripe();
  const elements = useElements();
  const { language } = useLanguage();
  const toast = useToast();
  const [isProcessing, setIsProcessing] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsProcessing(true);

    try {
      const result = await stripeService.confirmSetup(
        stripe,
        elements,
        clientSecret
      );

      if (result.success && result.paymentMethodId) {
        toast.success(language === 'zh-CN' ? '支付方式添加成功！' : 'Payment method added successfully!');
        onSuccess(result.paymentMethodId as string);
      } else {
        const errorMsg = typeof result.error === 'string' ? result.error : (language === 'zh-CN' ? '添加失败，请重试' : 'Failed to add, please try again');
        toast.error(errorMsg);
      }
    } catch (error) {
      console.error('Setup error:', error);
      toast.error(language === 'zh-CN' ? '处理失败' : 'Processing failed');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="mb-4">
        <p className="text-sm text-gray-600 dark:text-gray-400">
          {language === 'zh-CN' 
            ? '添加支付方式到您的账户，用于未来的快速支付。' 
            : 'Add a payment method to your account for faster checkout in the future.'}
        </p>
      </div>

      <div className="border border-gray-300 dark:border-gray-600 rounded-lg p-4 bg-white dark:bg-gray-700">
        <PaymentElement />
      </div>

      <div className="flex space-x-3 mt-6">
        <button
          type="button"
          onClick={onCancel}
          disabled={isProcessing}
          className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {language === 'zh-CN' ? '取消' : 'Cancel'}
        </button>
        <button
          type="submit"
          disabled={isProcessing || !stripe || !elements}
          className="flex-1 px-4 py-2 bg-gradient-to-r from-[#00d4ff] to-[#0f1c3f] text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isProcessing 
            ? (language === 'zh-CN' ? '处理中...' : 'Processing...') 
            : (language === 'zh-CN' ? '添加支付方式' : 'Add Payment Method')}
        </button>
      </div>
    </form>
  );
};

interface AddStripePaymentMethodModalProps {
  isOpen: boolean;
  onSuccess: (paymentMethodId: string) => void;
  onClose: () => void;
}

export const AddStripePaymentMethodModal = ({ isOpen, onSuccess, onClose }: AddStripePaymentMethodModalProps) => {
  const { language } = useLanguage();
  const toast = useToast();
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [stripePromise, setStripePromise] = useState<any>(null);

  useEffect(() => {
    // Load Stripe
    const loadStripeInstance = async () => {
      const stripe = await stripeService.getStripe();
      setStripePromise(stripe);
    };
    loadStripeInstance();
  }, []);

  useEffect(() => {
    if (isOpen && !clientSecret) {
      createSetupIntent();
    }
  }, [isOpen]);

  const createSetupIntent = async () => {
    setIsLoading(true);
    try {
      const result = await stripeService.createSetupIntent();
      if (result.success && result.clientSecret) {
        setClientSecret(result.clientSecret);
      } else {
        toast.error(language === 'zh-CN' ? '创建设置会话失败' : 'Failed to create setup session');
        onClose();
      }
    } catch (error) {
      console.error('Failed to create setup intent:', error);
      toast.error(language === 'zh-CN' ? '创建设置会话失败' : 'Failed to create setup session');
      onClose();
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setClientSecret(null);
    onClose();
  };

  const handleSuccess = (paymentMethodId: string) => {
    setClientSecret(null);
    onSuccess(paymentMethodId);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
          {language === 'zh-CN' ? '添加支付方式' : 'Add Payment Method'}
        </h3>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#00d4ff]"></div>
          </div>
        ) : clientSecret && stripePromise ? (
          <Elements
            stripe={stripePromise}
            options={{
              clientSecret,
              appearance: {
                theme: 'stripe',
                variables: {
                  colorPrimary: '#00d4ff',
                },
              },
            }}
          >
            <StripeSetupForm
              clientSecret={clientSecret}
              onSuccess={handleSuccess}
              onCancel={handleClose}
            />
          </Elements>
        ) : (
          <div className="text-center py-12">
            <p className="text-gray-600 dark:text-gray-400">
              {language === 'zh-CN' ? '加载表单...' : 'Loading form...'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};
